package com.wwtech.epp.ui.activity.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ninjia.ninjiabaselibrary.view.RxDialogWheelFiveCheck;
import com.ninjia.ninjiabaselibrary.view.RxDialogWheelYearMonthDayMe;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.base.BaseActivity;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.entity.AttachmentBean;
import com.wwtech.epp.entity.DynamicUI;
import com.wwtech.epp.entity.multi.PersonItem;
import com.wwtech.epp.ui.activity.work.component.DaggerDynamicAppComponent;
import com.wwtech.epp.ui.activity.work.contract.DynamicAppContract;
import com.wwtech.epp.ui.activity.work.module.DynamicAppModule;
import com.wwtech.epp.ui.activity.work.presenter.DynamicAppPresenter;
import com.wwtech.epp.utils.Dynamic.KeyValue;
import com.wwtech.epp.utils.ToastUtil;
import com.wwtech.epp.utils.UIUtils;
import com.wwtech.epp.view.CustomPopWindow;
import com.wwtech.epp.view.datepicker.NumericWheelAdapter;
import com.wwtech.epp.view.datepicker.WheelView;
import com.wwtech.epp.view.dynamicapp.AttachementAppView;
import com.wwtech.epp.view.dynamicapp.ButtonAppView;
import com.wwtech.epp.view.dynamicapp.ContactsAppView;
import com.wwtech.epp.view.dynamicapp.DatepickerAppView;
import com.wwtech.epp.view.dynamicapp.RadioAppView;
import com.wwtech.epp.view.dynamicapp.TextAppView;
import com.wwtech.epp.view.dynamicapp.TextviewAppView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.wwtech.epp.ui.adapter.main.CheckPersonAdapter.TYPE_PERSON;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/09/18 21:54:46
 */

public class DynamicAppActivity extends BaseActivity implements DynamicAppContract.View {

    @Inject
    DynamicAppPresenter mPresenter;
    String dynamicUI;
    ArrayList<DynamicUI.DataBean> uiList;
    LinkedHashMap<String, View> viewMap;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    private RxDialogWheelYearMonthDayMe mRxDialogWheelYearMonthDay;
    private WheelView wheelView;
    private NumericWheelAdapter xiangmuAdapter;
    private ArrayList<String> datalist;
    private RxDialogWheelFiveCheck mRxDialogWheelFiveCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_dynamic_app);
        ButterKnife.bind(this);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initData() {
        viewMap = new LinkedHashMap<>();
        setTitle(getIntent().getStringExtra("title"));
//        mPresenter.getUIDesc(getIntent().getStringExtra("dataId"), new HashMap<String, String>());
        if (getIntent().getStringExtra("dynamicUI").equals("")) {
            return;
        }
        dynamicUI = "{\"data\":" + getIntent().getStringExtra("dynamicUI") + "}";
        KLog.i(dynamicUI);
        Gson gson = new Gson();
        uiList = gson.fromJson(dynamicUI, DynamicUI.class).getData();
        for (int i = 0; i < uiList.size(); i++) {
            int position = i;
            switch (uiList.get(i).getName()) {
                case "text":
                    TextAppView textAppView = new TextAppView(DynamicAppActivity.this);
                    textAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("text" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        textAppView.setLayoutParams(layoutParams);
                    }
                    textAppView.setKey("text" + i);
                    viewMap.put("text" + i, textAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(textAppView);
                    break;
                case "textview":
                    TextviewAppView textviewAppView = new TextviewAppView(DynamicAppActivity.this);
                    textviewAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("textview" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        textviewAppView.setLayoutParams(layoutParams);
                    }
                    textviewAppView.setKey("textview" + i);
                    viewMap.put("textview" + i, textviewAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(textviewAppView);
                    break;
                case "datepicker":
                    DatepickerAppView datepickerAppView = new DatepickerAppView(DynamicAppActivity.this);
                    datepickerAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("datepicker" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        datepickerAppView.setLayoutParams(layoutParams);
                    }
                    datepickerAppView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (uiList.get(position).getFormat().equals("yyyy-MM-dd HH:mm")) {
                                showDatepickerFiveCheck("datepicker" + position);
                                mRxDialogWheelFiveCheck.show();
                            } else {
                                showDatepicker("datepicker" + position);
                                mRxDialogWheelYearMonthDay.show();
                            }
                        }
                    });
                    datepickerAppView.setKey("datepicker" + i);
                    viewMap.put("datepicker" + i, datepickerAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(datepickerAppView);
                    break;
                case "radio":
                    RadioAppView radioAppView = new RadioAppView(DynamicAppActivity.this);
                    radioAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("radio" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        radioAppView.setLayoutParams(layoutParams);
                    }
                    radioAppView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            datalist = uiList.get(position).getOption();
                            xiangmuAdapter = new NumericWheelAdapter(DynamicAppActivity.this, 0, datalist.size() - 1, "", datalist);
                            xiangmuAdapter.setTextSize(15);
                            showWheelView(radioAppView, uiList.get(position).getPlacehold(), "radio" + position);
                        }
                    });
                    radioAppView.setKey("radio" + i);
                    viewMap.put("radio" + i, radioAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(radioAppView);
                    break;
                case "contacts":
                    ContactsAppView contactsAppView = new ContactsAppView(DynamicAppActivity.this);
                    contactsAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("contacts" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        contactsAppView.setLayoutParams(layoutParams);
                    }
                    contactsAppView.setKey("contacts" + i);
                    viewMap.put("contacts" + i, contactsAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(contactsAppView);
                    break;
                case "attachment":
                    AttachementAppView attachementAppView = new AttachementAppView(DynamicAppActivity.this);
                    attachementAppView.setDataBean(uiList.get(i));
                    if (viewMap.get("attachment" + (i - 1)) == null && i != 0) {
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.setMargins(0, UIUtils.dip2px(20), 0, 0);
                        attachementAppView.setLayoutParams(layoutParams);
                    }
                    attachementAppView.setKey("attachment" + i);
                    viewMap.put("attachment" + i, attachementAppView);
                    KLog.i("添加" + i);
                    llRoot.addView(attachementAppView);
                    break;
                default:
                    break;
            }
        }
        ButtonAppView buttonAppView = new ButtonAppView(DynamicAppActivity.this);
        buttonAppView.getTijiao().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KLog.i("点击啦");
                preData();
            }
        });
        viewMap.put("button", buttonAppView);
        llRoot.addView(buttonAppView);
    }

    private void preData() {
        Map<String, String> uploadMap = new LinkedHashMap<>();
        ArrayList<KeyValue> list = new ArrayList<>();
        for (String key : viewMap.keySet()) {
            KLog.i(key);
            if (viewMap.get(key).getClass() == TextAppView.class) {
                KLog.i("循环到了TextAppView");
                TextAppView textAppView = (TextAppView) viewMap.get(key);
                if (textAppView.getDataBean().isValidate()) {
                    if (textAppView.getContent().getText().toString().trim().equals("") || textAppView.getContent().getText() == null) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                }
                list.add(new KeyValue(textAppView.getDataBean().getTitle(), textAppView.getContent().getText().toString().trim()));
                uploadMap.put(textAppView.getDataBean().getTitle(), textAppView.getContent().getText().toString().trim());
            } else if (viewMap.get(key).getClass() == TextviewAppView.class) {
                KLog.i("循环到了TextviewAppView");
                TextviewAppView textviewAppView = (TextviewAppView) viewMap.get(key);
                if (textviewAppView.getDataBean().isValidate()) {
                    if (textviewAppView.getEditText().getText().toString().trim().equals("")) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                }
                list.add(new KeyValue(textviewAppView.getDataBean().getTitle(), textviewAppView.getEditText().getText().toString().trim()));
                uploadMap.put(textviewAppView.getDataBean().getTitle(), textviewAppView.getEditText().getText().toString().trim());
            } else if (viewMap.get(key).getClass() == ButtonAppView.class) {
                KLog.i("循环到了ButtonAppView");
            } else if (viewMap.get(key).getClass() == DatepickerAppView.class) {
                KLog.i("循环到了DatepickerAppView");
                DatepickerAppView datepickerAppView = (DatepickerAppView) viewMap.get(key);
                if (datepickerAppView.getDataBean().isValidate()) {
                    if (datepickerAppView.getContent().getText().toString().trim().equals("")) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                }
                list.add(new KeyValue(datepickerAppView.getDataBean().getTitle(), datepickerAppView.getContent().getText().toString().trim()));
                uploadMap.put(datepickerAppView.getDataBean().getTitle(), datepickerAppView.getContent().getText().toString().trim());
            } else if (viewMap.get(key).getClass() == ContactsAppView.class) {
                KLog.i("循环到了ContactsAppView");
                ContactsAppView contactsAppView = (ContactsAppView) viewMap.get(key);
                if (contactsAppView.getDataBean().isValidate()) {
                    if (contactsAppView.getPersonList().size() == 1) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                }
                String person = "";
                for (int j = 0; j < contactsAppView.getPersonList().size() - 1; j++) {
                    person += contactsAppView.getPersonList().get(j).getUserId() + ",";
                }
                if (!person.equals("")) {
                    person = person.substring(0, person.length() - 1);
                }
                list.add(new KeyValue(contactsAppView.getDataBean().getTitle(), person));
                uploadMap.put(contactsAppView.getDataBean().getTitle(), person);
            } else if (viewMap.get(key).getClass() == RadioAppView.class) {
                RadioAppView radioAppView = (RadioAppView) viewMap.get(key);
                if (radioAppView.getDataBean().isValidate()) {
                    if (radioAppView.getContent().getText().toString().equals("")) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                }
                list.add(new KeyValue(radioAppView.getDataBean().getTitle(), radioAppView.getContent().getText().toString().trim()));
                uploadMap.put(radioAppView.getDataBean().getTitle(), radioAppView.getContent().getText().toString());
            } else if (viewMap.get(key).getClass() == AttachementAppView.class) {
                AttachementAppView attachementAppView = (AttachementAppView) viewMap.get(key);
                if (attachementAppView.getDataBean().isValidate()) {
                    if (attachementAppView.getAttachmentUrl().equals("")) {
                        ToastUtil.displayShortToast("请完善内容");
                        return;
                    }
                } else {
                    if (!attachementAppView.getAttachmentUrl().equals("")) {
                        list.add(new KeyValue(attachementAppView.getDataBean().getTitle(), attachementAppView.getAttachmentUrl()));
                        uploadMap.put(attachementAppView.getDataBean().getTitle(), attachementAppView.getAttachmentUrl());
                    }
                }
            }
        }
        Map<String, String> map = new HashMap<>();
        KLog.i(list);
        map.put("data", JSONObject.toJSON(list).toString());
        KLog.i(map.get("data"));
        map.put("userId", ContainValue.userLogin.getData().getUserId() + "");
        map.put("appId", getIntent().getStringExtra("dataId"));
        mPresenter.upLoadData(map);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ContainValue.partPerson = null;
        for (int i = 0; i < ContainValue.userList.size(); i++) {
            if (ContainValue.userList.get(i).getItemType() == TYPE_PERSON) {
                PersonItem temp = (PersonItem) ContainValue.userList.get(i);
                if (!temp.type.equals("contact")) {
                    continue;
                }
                ((PersonItem) ContainValue.userList.get(i)).freind.setChecked(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mPresenter.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void setupActivityComponent() {
        DaggerDynamicAppComponent
                .builder()
                .appComponent(((AppConfig) getApplication()).getApplicationComponent())
                .dynamicAppModule(new DynamicAppModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(DynamicAppContract.DynamicAppContractPresenter presenter) {
        mPresenter = (DynamicAppPresenter) presenter;
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void onSetData(String key) {
        ContactsAppView contactsAppView = (ContactsAppView) viewMap.get(key);
        contactsAppView.setPersonList(ContainValue.partPerson);
        ContainValue.partPerson = null;
        contactsAppView.getPartMamberAdapter().notifyDataSetChanged();
    }

    @Override
    public void loadFileSuccess(AttachmentBean attachmentBean) {
        for (String key : viewMap.keySet()) {
            if (key.contains("attachment")) {
                AttachementAppView attachementAppView = (AttachementAppView) viewMap.get(key);
                attachementAppView.setNewData(attachmentBean);
            }
        }
    }

    private void showDatepicker(String key) {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDayMe(this, 0, 0);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        String time = mRxDialogWheelYearMonthDay.getSelectorYear() + "-" + mRxDialogWheelYearMonthDay.getSelectorMonth() + "-" + mRxDialogWheelYearMonthDay.getSelectorDay() + "";
                        DatepickerAppView datepickerAppView = (DatepickerAppView) viewMap.get(key);
                        datepickerAppView.getContent().setText(time);
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

    private void showDatepickerFiveCheck(String key) {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelFiveCheck = new RxDialogWheelFiveCheck(this, 0, 0);
        mRxDialogWheelFiveCheck.getTv_sure().setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        String time = mRxDialogWheelFiveCheck.getSelectorYear() + "-" + mRxDialogWheelFiveCheck.getSelectorMonth() + "-" + mRxDialogWheelFiveCheck.getSelectorDay() + " " + mRxDialogWheelFiveCheck.getSelectorHour() + ":" + mRxDialogWheelFiveCheck.getSelectorMinute();
                        DatepickerAppView datepickerAppView = (DatepickerAppView) viewMap.get(key);
                        datepickerAppView.getContent().setText(time);
                        mRxDialogWheelFiveCheck.cancel();
                    }
                });
        mRxDialogWheelFiveCheck.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelFiveCheck.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

    private void showWheelView(View showview, String title, String key) {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(showview.getWindowToken(), 0);
        View view = LayoutInflater.from(this).inflate(R.layout.wheelview_layout, null);
        LinearLayout ll_content = (LinearLayout) view.findViewById(R.id.ll_content);
        ll_content.setAnimation(AnimationUtils.loadAnimation(this, R.anim.pop_manage_product_in));
        TextView submit = (TextView) ll_content.findViewById(R.id.submit);
        TextView tv_title = (TextView) ll_content.findViewById(R.id.tv_title);
        tv_title.setText(title);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomPopWindow.onBackPressed();
                RadioAppView radioAppView = (RadioAppView) viewMap.get(key);
                radioAppView.getContent().setText(datalist.get(wheelView.getCurrentItem()));
            }
        });
        wheelView = (WheelView) ll_content.findViewById(R.id.wheelview);
        wheelView.setViewAdapter(xiangmuAdapter);
        new CustomPopWindow.PopupWindowBuilder(this)
                .setClippingEnable(false)
                .setFocusable(true)
                .setView(view)
                .setContenView(ll_content)
                .size(UIUtils.getDisplayWidth(this), UIUtils.getDisplayHeigh(this))
                .create()
                .showAtLocation(showview, Gravity.CENTER, 0, 0);
    }

}